package whu.cn.whushare.ui.main.known;

import java.util.List;

import whu.cn.whushare.R;
import whu.cn.whushare.common.UserManager;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.LoadingHelper;
import whu.cn.whushare.ui.common.MainReShowFragment;
import whu.cn.whushare.ui.main.MainTabActivity;
import whu.cn.whushare.ui.main.known.adapter.AllQuestionListAdapter;
import whu.cn.whushare.ui.main.known.bean.AllQuestion;
import whu.cn.whushare.ui.main.my.LoginActivity;
import whu.cn.whushare.util.Utils;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class KnownFragment extends MainReShowFragment {
	@ViewMapping(id = R.id.all_question_list)
	private PullToRefreshListView mRefreshListView;
	private AllQuestionListAdapter adapter;
	private LoadingHelper loadingHelper;
	private boolean mHasInited;
	private List<AllQuestion> mQuestions;
    private String mQuestionId;
    private long mQuestionCount;
	private int mCurPage = 1;
	private final static int PAGE_SIZE = 5;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		initParams();
		View root = inflater.inflate(R.layout.known_layout, container, false);
		initViews(root);
		return root;
	}

	private void initParams() {

	}

    //请求获取问题列表
	private void requestQuestionList(int page) {
		Downloader.getInstance(getActivity()).getAllQuestionList( page, PAGE_SIZE, this, page);
		loadingHelper.showLoadingView(mHasInited);
	}

	private void initViews(View root) {
		ViewMappingUtil.mapView(this, root);

        //设置顶部菜单条，没太懂，还
        getTopBarWithoutBack(root,R.id.top_bar);
        mTopBar.goBack.setVisibility(View.VISIBLE);
        mTopBar.goBack.setImageResource(R.drawable.search1);
		mTopBar.searchLayout.setVisibility(View.VISIBLE);
        mTopBar.searchView.setVisibility(View.INVISIBLE);
        mTopBar.searchTxt.setText("提问");
		((ViewGroup) mTopBar.searchLayout).setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
		mTopBar.searchView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
		mTopBar.searchView.setFocusable(true);
        mTopBar.searchView.setEnabled(false);
		for (int i = 0; i < mTopBar.searchView.getChildCount(); i++) {
            mTopBar.searchView.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(QuestionListActivity.getStartIntent(getActivity(), ""));
                }
            });
		}
		mTopBar.searchLayout.setOnClickListener(this);
		mRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
		mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> listViewPullToRefreshBase) {
				requestQuestionList(1);
				Utils.resetRefreshLabel(getActivity(), mRefreshListView);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> listViewPullToRefreshBase) {
				if (mCurPage * PAGE_SIZE >= mTotal) {
					Utils.setRefreshLabelToLast(getActivity(), mRefreshListView);
					Utils.COMMON_HANDLER.sendMessageDelayed(
							Message.obtain(Utils.COMMON_HANDLER, Utils.REFRESH_TO_COMPLETE, mRefreshListView), 500);
				} else {
					requestQuestionList(mCurPage + 1);
				}
			}
		});
	}

	@Override
    /**
     * 当网络请求成功时调用该方法
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param obj -
     * @see whu.cn.whushare.net.NetResponseListener#onSuccess(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result<T>, java.lang.Object)
     */
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
		mCurPage = (int) obj;
		switch (type) {
		case ALL_QUESTION_LIST:
			List<AllQuestion> questions = (List<AllQuestion>) response;

			if (adapter == null || mCurPage == 1) {
				mQuestions = questions;

				adapter = new AllQuestionListAdapter(getActivity(), mQuestions);
				mRefreshListView.setAdapter(adapter);
			} else {

				mQuestions.addAll(questions);

				adapter.notifyDataSetChanged();
			}

			mHasInited = true;
			loadingHelper.showContentView();
			mRefreshListView.onRefreshComplete();

			break;
		default:
			break;
		}
	}

	@Override
    /**
     * 当网络请求失败时调用该方法
     * @param type - URL类型
     * @param response - 返回结果信息
     * @param error -
     * @see whu.cn.whushare.net.NetResponseListener#onFail(whu.cn.whushare.net.DownloadParams.PARSING_TYPE, whu.cn.whushare.bean.Result, com.android.volley.VolleyError)
     */
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		if (!mHasInited) {
			loadingHelper.showRetryView();
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		initActions();
		loadingHelper = new LoadingHelper(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				requestQuestionList(mCurPage);
			}
		});
		loadingHelper.onCreateView(LayoutInflater.from(getActivity()), mRefreshListView);
      //  requestQuestionList(mCurPage);
	}

	private void initActions() {
		mTopBar.searchTxt.setOnClickListener(this);
        mTopBar.goBack.setOnClickListener(this);
		mRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				AllQuestion allQuestion = (AllQuestion) adapter.getItem(arg2 - 1);
			    mQuestionId = String.valueOf(allQuestion.getQuestion().getId());
                mQuestionCount=allQuestion.getAnswerNum();
				startActivityForResult(QuestionDetailActivity.getStartIntent(getActivity(), mQuestionId), 1);
			}

		});

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.go_back_btn:
        startActivity(QuestionListActivity.getStartIntent(getActivity(),"question"));
			break;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!UserManager.getInstance(getActivity()).hasLogin()) {
			toast(R.string.un_login);
			startActivityForResult(LoginActivity.getStartIntent(getActivity()), 2);
		} else {
			if (!mHasInited) {
				requestQuestionList(mCurPage);
			}
		}
	}

	@Override
    /**
     * 当
     */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 2) {
			if (!UserManager.getInstance(getActivity()).hasLogin()) {
				toast("您还没登陆，将跳转至个人主页");
				((MainTabActivity) getActivity()).selectTab(3);
			}
		}
	}
}
